Page({
  data: {
    notes: []
  },

  onLoad() {
    this.loadNotes();
  },

  onPullDownRefresh() {
    this.loadNotes();
    wx.stopPullDownRefresh();
  },

  loadNotes() {
    const notes = wx.getStorageSync('notes') || [];
    this.setData({ notes });
  },

  addNote() {
    wx.navigateTo({
      url: '/pages/create/create'
    });
  },

  openNote(e) {
    const { id } = e.currentTarget.dataset;
    const note = this.data.notes.find(n => n.id === id);
    wx.navigateTo({
      url: `/pages/modify/modify?id=${id}&title=${note.title}&content=${note.content}`
    });
  },

  deleteNote(e) {
    const { id } = e.currentTarget.dataset;
    wx.showModal({
      title: '删除提示',
      content: '确定要删除这个笔记吗?',
      success: (res) => {
        if (res.confirm) {
          this.removeNote(id);
        }
      }
    });
  },

  removeNote(id) {
    const notes = this.data.notes.filter(note => note.id !== id);
    this.setData({ notes });
    wx.setStorageSync('notes', notes);
  }
});
